package com.yexiao.cofe.business.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.yexiao.cofe.business.mapper.ParamItemMapper;
import com.yexiao.cofe.business.mapper.ParamValueMapper;
import com.yexiao.cofe.business.pojo.ParamItem;
import com.yexiao.cofe.business.pojo.ParamValue;
import com.yexiao.cofe.business.service.ParamValueService;
import com.yexiao.cofe.common.exception.BusinessException;
import com.yexiao.core.util.JSONUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author lkl
 * @since 2025/3/31
 */
@Service
public class ParamValueServiceImpl implements ParamValueService {

    @Resource
    private ParamItemMapper paramItemMapper;
    @Resource
    private ParamValueMapper paramValueMapper;

    @Override
    public void addParamValue(JSONObject param) {
        Integer paramItemId = JSONUtil.checkAndGetInt(param, "paramItemId");
        String value = JSONUtil.checkAndGetStr(param, "value");
        String priceOffset = JSONUtil.checkAndGetStr(param, "priceOffset");
        Integer stock = JSONUtil.getInt(param, "stock");

        ParamItem paramItem = paramItemMapper.selectById(paramItemId);
        if(paramItem == null) {
            throw new BusinessException("参数项不存在");
        }

        ParamValue paramValue = new ParamValue();
        paramValue.setParamItemId(paramItemId)
                .setValue(value)
                .setPriceOffset(new BigDecimal(priceOffset))
                .setStock(stock);
        paramValueMapper.insert(paramValue);

    }

    @Override
    public void deleteParamValue(JSONObject param) {
        Integer id = JSONUtil.checkAndGetInt(param, "id");
        paramValueMapper.deleteById(id);
    }

    @Override
    public void modifyParamValue(JSONObject param) {
        Integer id = JSONUtil.checkAndGetInt(param, "id");
        Integer paramItemId = JSONUtil.getInt(param, "paramItemId");
        String value = JSONUtil.getStr(param, "value");
        String priceOffset = JSONUtil.getStr(param, "priceOffset");
        Integer stock = JSONUtil.getInt(param, "stock");

        BigDecimal price = new BigDecimal(priceOffset);

        paramValueMapper.modifyParamValue(id, paramItemId, value, price, stock);
    }
}
